<template>
  <div class="section">
    <h2>社交媒体使用情况</h2>
    <div class="chart-container">
      <div id="platformChart" class="chart"></div>
      <div id="usageDistChart" class="chart"></div>
      <div id="academicImpactChart" class="chart"></div>
      <div id="addictionLevelsChart" class="chart"></div>
    </div>
  </div>
  <div class="sectiona">
    <h2>社交媒体使用时长分析</h2>
    <div class="chart-containera">
      <div id="usageChart" class="charta"></div>
    </div>
  </div>
</template>
<script>
import * as echarts from "echarts"; // 引入echarts库
import Papa from "papaparse"; // 引入PapaParse库用于解析CSV文件

export default {
  name: "SocialMedia", // 组件名称

  data() {
    return {
      loading: true, // 数据加载状态
      stats: {
        usage: {
          Yes: [3.2, 5.8, 4.4, 5.4, 8.5], // 使用社交媒体的平均每日时长
          No: [1.5, 3.2, 3.7, 4.3, 5.2], // 不使用社交媒体的平均每日时长
        },
      },
    };
  },

  mounted() {
    // 箱线图
    const usageChart = echarts.init(document.getElementById("usageChart"));
    usageChart.setOption({
      title: {
        text: "平均每日使用时长箱线图", // 图表标题
      },
      tooltip: {
        trigger: "axis", // 鼠标悬停显示提示框
      },
      grid: {
        left: "10%",
        right: "10%",
        top: "15%",
        bottom: "15%", // 设置图表的边距
      },
      xAxis: {
        type: "category",
        data: ["Yes", "No"], // 横轴数据：是否使用社交媒体
        name: "是否受到影响",
        nameLocation: "middle",
        nameGap: 30,
        axisLabel: {
          interval: 0, // 横轴标签不跳跃显示
        },
      },
      yAxis: {
        type: "value",
        name: "平均每日使用时长 (小时)",
        min: 0, // 设置y轴的最小值
      },
      series: [
        {
          name: "平均每日使用时长",
          type: "boxplot", // 箱线图类型
          data: [this.stats.usage.Yes, this.stats.usage.No],
          itemStyle: {
            color: "#4a90e2", // 设置图表颜色
          },
          tooltip: {
            formatter: (params) => {
              // 定义提示框的格式
              return `最大值: ${params.data[5]}<br/>上四分位数: ${params.data[4]}<br/>中位数: ${params.data[3]}<br/>下四分位数: ${params.data[2]}<br/>最小值: ${params.data[1]}`;
            },
          },
        },
      ],
    });

    this.initCharts(); // 确保图表在组件挂载后初始化
  }, //mounted

  methods: {
    async initCharts() {
      this.loading = true; // 开始加载数据
      const charts = {
        platformChart: echarts.init(document.getElementById("platformChart")),
        usageDistChart: echarts.init(document.getElementById("usageDistChart")),
        academicImpactChart: echarts.init(document.getElementById("academicImpactChart")),
        addictionLevelsChart: echarts.init(document.getElementById("addictionLevelsChart")),
      };

      // 加载CSV数据：平台使用情况
      Papa.parse("/data/Students Social Media Addiction.csv", {
        download: true,
        header: true, // 启用CSV头部
        complete: (results) => {
          const data = results.data;

          // 统计平台使用频率
          const platformCount = {};
          //统计平均使用时长
          const usageTimeCounts = {
            2: 0,
            3: 0,
            4: 0,
            5: 0,
            6: 0,
            7: 0,
          };
          //对学业影响Yes/No
          const Impact = {};
          //成瘾分布情况
          const Addiction = {};

          data.forEach((row) => {
            //创建常量
            const platform = row.Most_Used_Platform;
            const user_time = row.Avg_Daily_Usage_Hours;
            const impact = row.Affects_Academic_Performance;
            const addiction = row.Addicted_Score;
            //平台使用情况
            if (platform) {
              platformCount[platform] = (platformCount[platform] || 0) + 1;
            }
            //平均使用时间
            if (user_time != null) {
              if (user_time <= 2) {
                usageTimeCounts["2"]++;
              } else if (user_time <= 3) {
                usageTimeCounts["3"]++;
              } else if (user_time <= 4) {
                usageTimeCounts["4"]++;
              } else if (user_time <= 5) {
                usageTimeCounts["5"]++;
              } else if (user_time <= 6) {
                usageTimeCounts["6"]++;
              } else {
                usageTimeCounts["7"]++;
              }
            }
            //对学业影响Yes/No
            if (impact) {
              Impact[impact] = (Impact[impact] || 0) + 1;
            }
            //影响分布
            Addiction[addiction] = (Addiction[addiction] || 0) + 1;
          });

          this.loading = false; // 数据加载完毕

          // 更新平台使用情况饼图
          charts.platformChart.setOption({
            title: { text: "最常用社交平台" },
            tooltip: { trigger: "item" },
            legend: { orient: "vertical", left: "left", top: "30px" },
            series: [
              {
                type: "pie",
                radius: "60%",
                center: ["60%", "50%"],
                label: { show: false, formatter: "{b}: {c} ({d}%)" },
                data: Object.entries(platformCount).map(([name, value]) => ({
                  name,
                  value,
                })),
              },
            ],
          });

          //使用时长分布柱状图
          charts.usageDistChart.setOption({
            title: { text: "每日使用时长分布" },
            tooltip: {},
            xAxis: {
              type: "category",
              data: Object.keys(usageTimeCounts).sort((a, b) => a - b),
              name: "小时",
            },
            yAxis: { type: "value", name: "人数" },
            series: [
              {
                data: Object.keys(usageTimeCounts)
                  .sort((a, b) => a - b)
                  .map((key) => usageTimeCounts[key]),
                type: "bar",
                color: "#5470c6", // 设置柱状图颜色
              },
            ],
          });
          // 是否对学业影响饼图
          charts.academicImpactChart.setOption({
            title: { text: "对学业的影响" },
            tooltip: { trigger: "item" },
            legend: { orient: "vertical", left: "left", top: "30px" },
            series: [
              {
                type: "pie",
                radius: "60%",
                data: Object.entries(Impact).map(([name, value]) => ({
                  name,
                  value,
                })),
              },
            ],
          });
          // 成瘾程度分布柱状图
          charts.addictionLevelsChart.setOption({
            title: { text: "成瘾程度分布" },
            tooltip: {},
            grid: {
              right: "10%", //右边距
            },
            xAxis: {
              type: "category",
              data: Object.keys(Addiction).sort((a, b) => a - b),
              name: "成瘾程度",
            },
            yAxis: { type: "value", name: "人数" },
            series: [
              {
                data: Object.keys(Addiction)
                  .sort((a, b) => a - b)
                  .map((key) => Addiction[key]),
                type: "bar",
                color: "#ee6666", // 设置柱状图颜色
              },
            ],
          });
        }, //complete
        error: (err) => {
          console.error("CSV加载失败:", err);
        },
      }); //异步加载
    }, // initCharts方法结束
  }, // methods结束
}; // export default结束
</script>

<style scoped>
.section {
  background: white;
  border-radius: 35px;
  padding: 20px;
  margin-bottom: 30px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  margin-left: 15px;
  margin-right: 15px;
}

.section h2 {
  color: #4a90e2;
  margin-top: 0;
  padding-bottom: 10px;
  border-bottom: 2px solid var(--border-color);
}

.chart-container {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20px;
  margin-top: 20px;
}

@media (max-width: 768px) {
  .chart-container {
    grid-template-columns: 1fr;
  }
}

.chart {
  height: 400px;
  border-radius: 10px;
  padding: 15px;
  background: white;
}
.sectiona {
  background: white;
  border-radius: 35px;
  padding: 20px;
  margin-bottom: 30px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  margin-left: 15px;
  margin-right: 15px;
}

.sectiona h2 {
  color: #4a90e2;
  margin-top: 0;
  padding-bottom: 10px;
  border-bottom: 2px solid var(--border-color);
}

.chart-containera {
  display: grid;
  grid-template-columns: 1fr;
  gap: 20px;
  margin-top: 20px;
}

.charta {
  height: 400px;
  border-radius: 10px;
  padding: 15px;
  background: white;
}
</style>
